package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"new_ginblog/internal/middleware"
	"new_ginblog/internal/utils/errormsg"
	"time"
)

// RefreshToken 用于刷新access token的函数
func RefreshToken(c *gin.Context) {
	// 从请求头里的 X-Refresh-Token 参数中读取refresh token
	tokenHeader := c.Request.Header.Get("X-Refresh-Token")
	code := errormsg.SUCCESS
	if tokenHeader == "" {
		code = errormsg.ERROR_TOKEN_NOT_EXIST
		c.JSON(code, gin.H{
			"code": code,
			"msg":  errormsg.GetErrorMsg(code),
		})
		c.Abort()
		return
	}

	key, tCode := middleware.CheckRefreshToken(tokenHeader)
	if tCode != errormsg.SUCCESS {
		code = errormsg.ERROR_TOKEN_WRONG
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  errormsg.GetErrorMsg(code),
		})
		c.Abort()
		return
	}

	// 检查token是否过期
	if key.ExpiresAt != nil && key.ExpiresAt.Before(time.Now()) {
		code = errormsg.ERROR_REFRESH_TOKEN_RUNTIME
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  errormsg.GetErrorMsg(code),
		})
		c.Abort()
		return
	}

	c.Set("username", key.Username)

	// 调用setAccessToken函数注册新的access Token
	accessToken, accessCode := middleware.SetAccessToken(key.Username)
	c.JSON(http.StatusOK, gin.H{
		"code":         accessCode,
		"msg":          errormsg.GetErrorMsg(code),
		"access_token": accessToken,
	})
}
